package com.pushway.demo.service;

import com.pushway.demo.pojo.PushItem;
import io.prometheus.client.exporter.PushGateway;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chentiefeng
 * 参考：https://github.com/prometheus/client_java
 */
@Slf4j
public class PushGatewayService {

    private PushGateway pushGateway = null;

    /**
     * 初始化PushGateway实例
     */
    public void init(String pushGatewayHost) {
        pushGateway = new PushGateway(pushGatewayHost);
    }

    /**
     * 推送监控数据
     * @param pushItem
     * @return
     */
    public boolean push(PushItem pushItem) {
        boolean resultFlag = true;
        Map<String, String> groupingKey = new HashMap<>(1);
        groupingKey.put("instance", pushItem.getInstance());
        try {
            // pushAdd()可以添加指标到同一个instance和job下，push()会重新刷新同一个instance和job下的所有指标
            pushGateway.pushAdd(pushItem.getCollector(), pushItem.getJob(), groupingKey);
        } catch (IOException e) {
            log.error("Push PushGateway[{}-{}] failed", pushItem.getInstance(), pushItem.getJob(), e);
            resultFlag = false;
        }
        return resultFlag;
    }
}
